package example;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.DatagramPacket;
 
public class UdpServer {
    private int port;
 
    public UdpServer(int port) {
        this.port = port;
    }
 
    public void start() throws Exception {
        Bootstrap b = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        b.group(group)
         .channel(NioDatagramChannel.class)
         .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
             @Override
             protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
                 String msg = packet.content().toString(io.netty.util.CharsetUtil.UTF_8);
                 System.out.println("Received message: " + msg);

                 String responseMessage = "Received your message and this is a reply!";
                 ByteBuf responseBuf = ctx.alloc().buffer(responseMessage.getBytes().length);
                 responseBuf.writeBytes(responseMessage.getBytes());
                 ctx.writeAndFlush(responseBuf);
             }
         });

        ChannelFuture sync = b.bind(port).sync().channel().closeFuture().sync();
    }
 
    public static void main(String[] args) throws Exception {
        UdpServer server = new UdpServer(9999);
        server.start();
    }
}